package com.chy.blog_server.modular.map.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chy.blog_server.core.util.DateUtil;
import com.chy.blog_server.core.util.GetUserIpAddressUtil;
import com.chy.blog_server.core.util.PageAndParamUtil;
import com.chy.blog_server.core.util.StringUtil;
import com.chy.blog_server.modular.map.entity.MapDistrict;
import com.chy.blog_server.modular.map.entity.MapLog;
import com.chy.blog_server.modular.map.entity.MapMerchantInfo;
import com.chy.blog_server.modular.map.export.DynamicExcelUtil;
import com.chy.blog_server.modular.map.service.IMapMerchantInfoService;
import com.chy.blog_server.modular.map.service.impl.MapDistrictServiceImpl;
import com.chy.blog_server.modular.map.service.impl.MapLogServiceImpl;
import com.chy.blog_server.modular.web.entity.BoContent;
import com.chy.blog_server.modular.web.service.IBoContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * 描述：高德/百度地图商家信息 开放端controller
 * 作者：chenhuiyan
 * 时间：2025/03/22 22:07
 */
@Controller
@RequestMapping(value = "/map/publicIndex")
public class PublicMapMerchantInfoController {

    /**
     * 前缀
     */
    private static String PREFIX = "map/publicMapMerchantInfo/";

    @Autowired
    private IMapMerchantInfoService mapMerchantInfoService;

    @Autowired
    private MapDistrictServiceImpl mapDistrictService;

    @Autowired
    private IBoContentService boContentService;

    @Autowired
    private MapLogServiceImpl mapLogService;

    /**
     * 开放端首页
     * @return
     */
    @RequestMapping(value = "")
    public String publicIndex(){
        return PREFIX + "publicMapMerchantInfo";
    }

    /**
     * 获取商家信息
     * @return
     */
    @RequestMapping(value = "/getGdMerchantInfo")
    @ResponseBody
    public Map<String, Object> getMerchantInfo(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            String province = params.get("province") + ""; // 省份
            String city = params.get("city") + ""; // 城市
//            String area = params.get("area") + "";  // 区/县
            String keyword = params.get("keyword") + "";  // 搜索关键词
            String dataSource = params.get("dataSource") + ""; //数据来源
            String serverKey = params.get("serverKey") + ""; //密码
            String logCode = params.get("logCode") + ""; //日志编号
            String getType = params.get("getType") + ""; //抓取类型：1信息库中抓取，2重新抓取高徳
            if(StringUtil.isNull(serverKey)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【安全密码】</span>");
            } else if(StringUtil.isNull(province)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【省份】全称</span>");
            }else if(StringUtil.isNull(city)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【城市】全称</span>");
            }else if(StringUtil.isNull(keyword)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【关键词】</span>");
            } else if (StringUtil.isNull(dataSource)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择数据来源【数据来源】</span>");
            } else if (StringUtil.isNull(logCode)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>日志编号异常</span>");
            } else if (StringUtil.isNull(getType)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择【抓取类型】</span>");
            } else{
                //查询前先进行密码验证
                boolean flag = validPassword(serverKey);
                if(!flag){
                    res.put("state", "500");
                    res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>【安全密码】不正确</span>");
                }else{
                    if("gaode".equals(dataSource)){
                        List<Map<String, Object>> list = mapMerchantInfoService.getMerchantInfo(request, params); //获取数据列表
                        Integer count = mapMerchantInfoService.getCount(params); //获取总数
                        if(count == 0){
                            res.put("code", 500);
                            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>信息库没有数据，请选择【城市】、【关键词】查询</span>");
                        }else{
                            res.put("code", 0);
                            res.put("msg", "获取数据成功");
                            res.put("count", count);
                            res.put("data", list);
                        }
                    }else{
                        res.put("code", 500);
                        res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>百度数据获取功能未上线</span>");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>" + e.getMessage() + "</span>");
        }
        return res;
    }

    /**
     * 获取商家信息总数据量
     * @return
     */
    @RequestMapping(value = "/getMerchantInfoTotal")
    @ResponseBody
    public Map<String, Object> getMerchantInfoTotal(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = new HashMap<>();
            params.put("dataSource", "gaode");
            Integer gdCount = mapMerchantInfoService.getCount(params); //获取高徳商家总数
            res.put("code", 0);
            res.put("msg", "获取数据成功");
            res.put("gdCount", gdCount);
            res.put("bdCount", 0);
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>" + e.getMessage() + "</span>");
        }
        return res;
    }

    /**
     * 获取当前城市商家信息总数据量
     * @return
     */
    @RequestMapping(value = "/getCityMerchantInfoTotal")
    @ResponseBody
    public Map<String, Object> getCityMerchantInfoTotal(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            String province = params.get("province") + ""; // 省份
            String city = params.get("city") + ""; // 城市
//            String area = params.get("area") + "";  // 区/县
            String keyword = params.get("keyword") + "";  // 搜索关键词
            String dataSource = params.get("dataSource") + ""; //数据来源
            if(StringUtil.isNull(province)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【省份】全称</span>");
            }else if(StringUtil.isNull(city)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【城市】全称</span>");
            }else if(StringUtil.isNull(keyword)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【关键词】</span>");
            } else if (StringUtil.isNull(dataSource)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择数据来源【数据来源】</span>");
            }else{
                //获取省份和城市中文名称
                MapDistrict provinceDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "province").eq("adcode", province));
                String provinceName = provinceDistrict.getName(); // 省份中文名称
                String cityName = ""; // 城市中文名称
                if(province.equals(city)){
                    cityName = provinceDistrict.getName();
                }else{
                    MapDistrict cityDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "city").eq("adcode", city));
                    cityName = cityDistrict.getName();
                }
                params.put("province", provinceName);
                params.put("city", cityName);
                Integer count = mapMerchantInfoService.getCount(params); //获取商家总数
                res.put("code", 0);
                res.put("msg", "获取数据成功");
                res.put("count", count);
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>" + e.getMessage() + "</span>");
        }
        return res;
    }

    /**
     * 获取当前城市商家信息总数据量(高徳/百度)
     * @return
     */
    @RequestMapping(value = "/getCityGdBdMerchantInfoTotal")
    @ResponseBody
    public Map<String, Object> getCityGdBdMerchantInfoTotal(HttpServletRequest request){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            String province = params.get("province") + ""; // 省份
            String city = params.get("city") + ""; // 城市
//            String area = params.get("area") + "";  // 区/县
            String keyword = params.get("keyword") + "";  // 搜索关键词
            if(StringUtil.isNull(province)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【省份】全称</span>");
            } else if (StringUtil.isNull(city)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【城市】全称</span>");
            } else if (StringUtil.isNull(keyword)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【关键词】</span>");
            } else {
                //获取省份和城市中文名称
                MapDistrict provinceDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "province").eq("adcode", province));
                String provinceName = provinceDistrict.getName(); // 省份中文名称
                String cityName = ""; // 城市中文名称
                if(province.equals(city)){
                    cityName = provinceDistrict.getName();
                }else{
                    MapDistrict cityDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "city").eq("adcode", city));
                    cityName = cityDistrict.getName();
                }
                params.put("province", provinceName);
                params.put("city", cityName);
                params.put("dataSource", "gaode");
                Integer gdCount = mapMerchantInfoService.getCount(params); //获取高徳商家总数
                params.put("dataSource", "baidu");
                Integer bdCount = mapMerchantInfoService.getCount(params); //获取百度商家总数
                String address = provinceName + cityName;
                if(provinceName.equals(cityName)){
                    address = provinceName;
                }
                res.put("code", 0);
                res.put("msg", "获取数据成功");
                res.put("address", address);
                res.put("gdCount", gdCount);
                res.put("bdCount", bdCount);
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>" + e.getMessage() + "</span>");
        }
        return res;
    }

    /**
     * 校验密码
     * @param serverKey
     * @return
     */
    public boolean validPassword(String serverKey){
        //内容保存密码的编号：0d1fa93118144bd3aceb151638aec78a
        BoContent boContent = boContentService.getById("0d1fa93118144bd3aceb151638aec78a");
        if(boContent.getTitle().equals(serverKey)){
            return true;
        }
        return false;
    }

    /**
     * 导出数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/exportData")
    public void exportData(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            String provinceCode = params.get("province") + ""; // 省份
            String cityCode = params.get("city") + ""; // 城市
//            String area = params.get("area") + "";  // 区/县
            String keyword = params.get("keyword") + "";  // 搜索关键词
            String dataSource = params.get("dataSource") + ""; //数据来源
            String serverKey = params.get("serverKey") + ""; //密码
            if(StringUtil.isNull(serverKey)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【密码】</span>");
            } else if(StringUtil.isNull(provinceCode)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择【省份】</span>");
            }else if(StringUtil.isNull(cityCode)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择【城市】</span>");
            } else if (StringUtil.isNull(dataSource)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择数据来源【数据来源】</span>");
            } else{
                //查询前先进行密码验证
                boolean flag = validPassword(serverKey);
                if(!flag){
                    res.put("state", "500");
                    res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>密码不正确</span>");
                }else{
                    if("gaode".equals(dataSource)){
                        //获取省份和城市中文名称
                        MapDistrict provinceDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "province").eq("adcode", provinceCode));
                        String province = provinceDistrict.getName(); // 省份中文名称
                        String city = ""; // 城市中文名称
                        if(provinceCode.equals(cityCode)){
                            city = provinceDistrict.getName();
                        }else{
                            MapDistrict cityDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "city").eq("adcode", cityCode));
                            city = cityDistrict.getName();
                        }
                        params.put("province", province);
                        params.put("city", city);
                        // 设置响应头
                        String fileName = URLEncoder.encode(province + city + "-(" + keyword + ")-高德商家信息", "UTF-8") + ".xlsx";
                        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                        response.setCharacterEncoding("utf-8");
                        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                        List<MapMerchantInfo> list = mapMerchantInfoService.listAllEntity(params);
                        List<Map<String, String>> exportData = new ArrayList<>();
                        for (MapMerchantInfo mapMerchantInfo: list){
                            Map<String, String> dataMap = new HashMap<>();
                            dataMap.put("商家名称", mapMerchantInfo.getName());
//                            dataMap.put("省市区/县", mapMerchantInfo.getProvince() + "-" + mapMerchantInfo.getCity() + "-" + mapMerchantInfo.getArea());
                            dataMap.put("地址", mapMerchantInfo.getAddress());
                            dataMap.put("电话", mapMerchantInfo.getTel());
                            dataMap.put("信息最后更新时间", DateUtil.getStringTime(mapMerchantInfo.getInfoUpdateTime()));
                            exportData.add(dataMap);
                        }

                        // 定义列宽规则，列不设置则自动计算宽度
                        Map<String, Integer> columnWidthMap = new HashMap<>();
                        columnWidthMap.put("商家名称", 30);     // 固定宽度30字符
                        columnWidthMap.put("地址", 60);     // 固定宽度30字符
                        columnWidthMap.put("电话", 30);  // 固定宽度30字符
                        columnWidthMap.put("信息最后更新时间", 25);  // 固定宽度25字符

                        String sheetName = "高德商家信息";
                        DynamicExcelUtil.exportToExcel(exportData, sheetName, response, columnWidthMap);

                        //添加导出日志
                        String logCode = String.valueOf(new Date().getTime());
                        int startIndex = 0; //默认0
                        int endIndex = list.size() - 1;
                        int totalNum = endIndex - startIndex + 1;
                        MapLog mapLog = mapLogService.createLogInfo(logCode, dataSource, "2", province, city, keyword, 0, endIndex, totalNum, "导出数据", GetUserIpAddressUtil.getIpAddress(request));
                        mapLogService.save(mapLog);
                    }else{
                        res.put("code", 500);
                        res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>百度数据获取功能未上线</span>");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>" + e.getMessage() + "</span>");
        }
    }

    /**
     * 校验数据是否被导出过
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkExportDataLog")
    @ResponseBody
    public Map<String, Object> checkExportDataLog(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> res = new HashMap<>();
        try{
            Map<String, Object> params = PageAndParamUtil.getParams();
            String provinceCode = params.get("province") + ""; // 省份
            String cityCode = params.get("city") + ""; // 城市
//            String area = params.get("area") + "";  // 区/县
            String keyword = params.get("keyword") + "";  // 搜索关键词
            String dataSource = params.get("dataSource") + ""; //数据来源
            String serverKey = params.get("serverKey") + ""; //密码
            if(StringUtil.isNull(serverKey)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请输入【密码】</span>");
            } else if(StringUtil.isNull(provinceCode)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择【省份】</span>");
            }else if(StringUtil.isNull(cityCode)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择【城市】</span>");
            } else if (StringUtil.isNull(dataSource)){
                res.put("code", 500);
                res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>请选择数据来源【数据来源】</span>");
            } else{
                //查询前先进行密码验证
                boolean flag = validPassword(serverKey);
                if(!flag){
                    res.put("state", "500");
                    res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>密码不正确</span>");
                }else{
                    if("gaode".equals(dataSource)){
                        //获取省份和城市中文名称
                        MapDistrict provinceDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "province").eq("adcode", provinceCode));
                        String province = provinceDistrict.getName(); // 省份中文名称
                        String city = ""; // 城市中文名称
                        if(provinceCode.equals(cityCode)){
                            city = provinceDistrict.getName();
                        }else{
                            MapDistrict cityDistrict = mapDistrictService.getOne(new QueryWrapper<MapDistrict>().eq("level", "city").eq("adcode", cityCode));
                            city = cityDistrict.getName();
                        }
                        List<MapLog> mapLogList = mapLogService.list(
                                new QueryWrapper<MapLog>()
                                        .eq("platform", dataSource)
                                        .eq("log_type", "2")
                                        .eq("province", province)
                                        .eq("city", city)
                                        .eq("keyworks", keyword));
                        res.put("code", 0);
                        if(!mapLogList.isEmpty()){
                            res.put("result", "error");
                            res.put("msg", province + city + "(关键词:" + keyword + ")：数据被导出过，确认还要导出吗？");
                        }else{
                            res.put("result", "ok");
                            res.put("msg", "数据未被导出过");
                        }
                    }else{
                        res.put("code", 500);
                        res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>百度数据获取功能未上线</span>");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            res.put("code", 500);
            res.put("msg", "<span style='color:red; font-size: 16px; font-weight: bolder;'>" + e.getMessage() + "</span>");
        }
        return res;
    }

}
